﻿using System;
using System.IO;
using UnityEngine;

public static class ExtTool {
	#region Transform

	public static void SetX(this Transform trans, float x)
	{
		trans.position = new Vector3(x, trans.position.y, trans.position.z);
	}

	public static void SetY(this Transform trans, float y)
	{
		trans.position = new Vector3(trans.position.x, y, trans.position.z);
	}

	public static void SetZ(this Transform trans, float z)
	{
		trans.position = new Vector3(trans.position.x, trans.position.y, z);
	}

	public static T FindComponentInChildren<T>(this Transform trans, string childName) where T : Component
	{
		Transform t = trans.Find(childName);
		try
		{
			return t.GetComponent<T>();
		}
		catch (Exception e)
		{
			MyLog.LogError("Cann't Get Component In Object : " + childName + " , " + (t == null));
			return null;
		}
	}

	#endregion

	#region GameObject

	public static T TryGetComponent<T>(this GameObject go) where T : Component
	{
		T component = go.GetComponent<T>();
		if (!component) {
			try {
				component = go.AddComponent<T>();
			} catch (Exception) {
				MyLog.LogError("Add Component Error : " + typeof(T));
			}
		}

		return component;
	}

	#endregion

	#region FileInfo

	/// <summary>
	/// File Name Without Extension
	/// </summary>
	public static string RealName(this FileInfo file) {
		string[] strs = file.Name.Split('.');
		string name = "";

		for (int i = 0; i < strs.Length - 1; i++) {
			name += strs[i];
			if (i < strs.Length - 2) {
				name += ".";
			}
		}

		return name;
	}

	/// <summary>
	/// Start With "Assets/"
	/// </summary>
	public static string AssetPath(this FileInfo file) {
		string str = "Assets" + file.FullName.Substring(Application.dataPath.Length);
		return str.RenamePath();
	}

	#endregion

	#region string

	public static string RenamePath(this string str) {
		return str = str.Replace('\\', '/');
	}

	public static bool CustomEndsWith(this string a, string b) {
		int ap = a.Length - 1;
		int bp = b.Length - 1;

		while (ap >= 0 && bp >= 0 && a[ap] == b[bp]) {
			ap--;
			bp--;
		}

		return (bp < 0 && a.Length >= b.Length) || (ap < 0 && b.Length >= a.Length);
	}

	public static bool CustomStartsWith(this string a, string b) {
		int aLen = a.Length;
		int bLen = b.Length;
		int ap = 0; int bp = 0;

		while (ap < aLen && bp < bLen && a[ap] == b[bp]) {
			ap++;
			bp++;
		}

		return (bp == bLen && aLen >= bLen) || (ap == aLen && bLen >= aLen);
	}

	#endregion
}
